<?php
/*********************************************************************\
*  Copyright (c) 1998-2013, TH. All Rights Reserved.
*  Author :lwj
*  FName  :ruku.php
*  Time   :2019.10.22
*  Remark :成品入库管理
\*********************************************************************/
FLEA::loadClass('TMIS_Controller');
class Controller_Sample_Ruku  extends TMIS_Controller {

    /**
     * 操作和查询的权限id
     * @var 参数类型
    */
    var $editFuckId = '1-1';
    var $listFuckId = '1-1';

    /**
     * 入库类型编码前缀
     * @var 参数类型
    */
    var $codePrev = 'SR';
    var $proPrev = 'OLP';
    var $kind = '样品入库';

    function __construct() {
        $this->_modelExample = FLEA::getSingleton('Model_Sample_Ruku');
        $this->_subModel = FLEA::getSingleton('Model_Sample_Ruku2Product');
        $this->_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');

        //导入的配置列
        $this->importCol = array(
            'proCode'   => '产品编号',
            'code'      => '条码',
            'proDesc'   => '花型颜色',
            'type'      => '样品类型',
            'kuweiName' => '库位',
            'cnt'       => '数量',
            'memoView'  => '备注说明'
        );
    }

    /**
     * 角色html配置form
     * Time：2018/12/13 15:49:40
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function _getMainFormItems($params = array() , & $field) {
        $fileds = $this->_modelKind->getFileds($params['kindId'] ,'all');
        // dump($params);exit;
        // $modelSupplier = FLEA::getSingleton('Model_Jichu_Supplier');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelGongyi = FLEA::getSingleton('Model_Jichu_Gongyi');
        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        //查出最大的条码号
        $sql = "SELECT code FROM sample_ruku2product where substr(code, -5) REGEXP '^[0-9]*$' group by code order by substr(code, -5) desc limit 0,1";
        $code = $this->_modelExample->findBySql($sql);

        $params = array();
        $mainFormItems = array(
            array(
                'type'        =>'comp-text',
                'name'        =>'rukuCode',
                'title'       =>'入库单号',
                'readonly'    =>true,
                'clearable'   =>true,
                'value'       =>'',
                // 'span'        =>'12',
                'placeholder' =>'系统自动生成，如：'.$this->createNewCode(),
            ),
            array(
                'type'      =>'comp-calendar',
                'name'      =>'rukuDate',
                'title'     =>'入库日期',
                'clearable' =>true,
                'value'     =>date('Y-m-d'),
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'creater',
                'title'     =>'操作人',
                'clearable' =>true,
                'readonly'  =>true,
                'value'     =>$_SESSION['REALNAME'],
            ),
            array(
                'type'      =>'comp-text',
                'name'      =>'reason',
                'title'     =>'来源',
                'clearable' =>true,
                'readonly'  =>false,
                'value'     =>'',
            ),
            array(
                'type'       =>'comp-autocomplete',
                'name'       =>'purpose',
                'title'      =>'用途',
                'value'      =>'',
                'clearable'  =>false,
                'options'    =>$this->_modelExample->getOptionsFiled('purpose'),
                'placeholder' =>'可输入可选择历史记录',
            ),
            array(
                'type'        =>'comp-textarea',
                'name'        =>'memo',
                'title'       =>'备注',
                'placeholder' =>'',
                'value'       =>'',
                'span'        =>8,
            ),

            array(
                'type'        =>'comp-message-alert',
                'name'        =>'alert_sample',
                'alertTitle'  =>'基础属性',
                'placeholder' =>'',
                'value'       =>'',
                'span'        =>24,
            ),
            array(
                'type'        =>'comp-alert',
                'name'        =>'alert_sample1',
                'alertTitle'  =>'已编最大条码号:'.$code[0]['code'],
                'placeholder' =>'',
                'value'       =>'',
                'span'        =>24,
            ),
            array(
                'type'        =>'comp-autocomplete',
                'name'        =>'code',
                'title'       =>'选择产品',
                'placeholder' =>'支持模糊搜索',
                'readonly'    =>false,
                'value'       =>'',
                'action'      =>url('Jichu_Product','GetOptionsCode',array('kindId'=>$_GET['kindId'])),
                // 'span'        =>'8',
                'valueKey'    =>'text',
                'append'      =>'留空自动生成'
            ),
            array(
                'type'        =>'comp-text',
                'name'        =>'proName',
                'title'       =>'产品名称',
                'value'       =>'',
                'span'        =>8,
            ),
        );
            // array(
            //     'type'       =>'comp-popup-select',
            //     'name'       =>'productId',
            //     'title'      =>'产品',
            //     'value'      =>'',
            //     'width'      =>"80%",
            //     'action'     =>url('Jichu_Product','ListPro'),
            //     'rowKey'     =>'id',
            //     'width'      =>'250',
            //     'dialogWidth'=>'80%',
            //     'displayKey' =>'productDesc',
            //     'displayText'=>'',
            //     'searchItems'=>array(
            //         'proCode' =>'',
            //         'proName' =>'',
            //     ),
            // ),
        //加载个性的部分
        if($fileds){
            foreach ($fileds as $key => $v) {
                if($v['showType'] == 'single'){
                    if($v['type'] == 'autocomplete'){
                        $mainFormItems[] = array(
                            'type'       =>'comp-autocomplete',
                            'name'       =>$v['filed'],
                            'title'      =>$v['title'],
                            'value'      =>'',
                            'clearable'  =>false,
                            'options'    =>$modelProduct->getColumnValues($v['filed'] ,$v['kindId']),
                            'placeholder' =>'可输入可选择历史记录',
                        );

                        $field[] = array('field'=>$v['filed'],'text'=>$v['title']);
                    }else{
                        $mainFormItems[] = array(
                            'type'      =>'comp-text',
                            'name'      =>$v['filed'],
                            'title'     =>$v['title'],
                            'clearable' =>true,
                            'value'     =>'',
                        );
                        $field[] = array('field'=>$v['filed'],'text'=>$v['title']);
                    }
                }
            }
        }
        $mainFormItems[] = array(
            'type'        =>'comp-message-alert',
            'name'        =>'alert_sample2',
            'alertTitle'  =>'附属属性',
            'placeholder' =>'',
            'value'       =>'',
            'span'        =>24,
        );
        $mainFormItems[] = array(
            'type'        =>'comp-autocomplete',
            'name'        =>'gexing',
            'title'       =>'格型',
            'placeholder' =>'',
            'readonly'    =>false,
            'value'       =>'',
            'action'      =>url('Sample_Ruku','GetOptionsKey',array('field'=>'gexing')),
        );
        $mainFormItems[] = array(
            'type'       =>'comp-autocomplete',
            'name'       =>'zuzhi',
            'title'      =>'组织',
            'value'      =>'',
            'clearable'  =>false,
            'options'    =>$this->_subModel->getOptionsFiled('zuzhi'),
            'placeholder' =>'可输入可选择历史记录',
        );
        $mainFormItems[] = array(
            'type'      =>'comp-text',
            'name'      =>'proDesc',
            'title'     =>'花型颜色',
            'readonly'  =>false,
            'value'     =>'',
            // 'append'    =>'颜色'
        );
        $mainFormItems[] = array(
            'type'       =>'comp-autocomplete',
            'name'       =>'type',
            'title'      =>'样品类型',
            'value'      =>'',
            'clearable'  =>false,
            'options'    =>$this->_modelExample->getTypeSelect(),
            'placeholder' =>'如A4，挂钩：用于统计不同类型的库存'
        );
        $mainFormItems[] = array(
            'type'        =>'comp-checkbox-group',
            'name'        =>'hzlId',
            'title'       =>'后整理工艺',
            'span'        =>'24',
            'readonly'    =>false,
            'value'       =>array(),
            'options'     =>$modelGongyi->getOptions(),
        );
        $mainFormItems[] = array(
            'type'        =>'comp-message-alert',
            'name'        =>'alert_sample3',
            'alertTitle'  =>'入库信息',
            'placeholder' =>'',
            'value'       =>'',
            'span'        =>24,
        );
        $mainFormItems[] = array(
            'type'       =>'comp-select',
            'name'       =>'kuweiId',
            'title'      =>'库位',
            'value'      =>'',
            'clearable'  =>false,
            'options'    =>$modelKuwei->getOptions(),
            'filterable' =>true,
            'multiple'   =>false
        );
        $mainFormItems[] = array(
            'type'      =>'comp-text',
            'name'      =>'cnt',
            'title'     =>'入库数量',
            'clearable' =>true,
            'value'     =>'',
        );
        $mainFormItems[] = array(
            'type'      =>'comp-text',
            'name'      =>'price',
            'title'     =>'单价',
            'clearable' =>true,
            'value'     =>'',
        );
        // $mainFormItems[] = array(
        //     'type'        =>'comp-text',
        //     'name'        =>'code',
        //     'title'       =>'条码',
        //     // 'span'        =>'16',
        //     'value'       =>'',
        //     'clearable'   =>false,
        //     'placeholder' =>'用于打印标签上的条码/二维码',
        //     'append'      =>'留空自动生成',
        // );
        $mainFormItems[] = array(
            'type'         =>'comp-image-phone-pull',
            'name'         =>'image2phone',
            'title'        =>'上传图片',
            'limit'        =>5,//最大允许上传个数
            'span'         =>24,
            'action'       =>$this->_url('UploadImage'),
            'actionRemove' =>$this->_url('RemoveImage'),//删除图片时需要从服务器删除,可以不定义
        );
        $rules = array(
            // 'rukuDate'=>array(
            //     array('required'=>true,'message'=>'入库日期必须'),
            // ),
            // // 'proCode'=>array(
            // //     array('required'=>true,'message'=>'产品编号必须'),
            // // ),
            // 'proName'=>array(
            //     array('required'=>true,'message'=>'产品名称必须'),
            // ),
            'kuweiId'=>array(
                array('required'=>true,'message'=>'库位必须'),
            ),
            'cnt'=>array(
                array('required'=>true,'message'=>'数量必须'),
            ),
            // 'reason'=>array(
            //     array('required'=>true,'message'=>'来源必须'),
            // ),
            // // 'code'=>array(
            // //     array('required'=>true,'message'=>'产品编号必须'),
            // // ),
            // 'proDesc'=>array(
            //     array('required'=>true,'message'=>'花型颜色必须'),
            // ),
            // 'type'=>array(
            //     array('required'=>true,'message'=>'样品类型必须'),
            // ),
            // 'image2phone'=>array(
            //     array('required'=>true,'message'=>'图片必须'),
            // ),
        );
        if($fileds){
            foreach ($fileds as $key => $v) {
                if($v['showType'] == 'single'){
                    if($v['isRequire'] == 'on'){
                        $rules[$v['filed']] = array(
                            array('required'=>true,'message'=>"{$v['title']}"."必须"),
                        );
                    }
                }
            }
        }

        // 不同的客户这里可能不一样，支持配置表混入
        include_once("Config/Ruku.config.php");
        if(isset($rule_config)){
            $rules = array_merge($rules , $rule_config);
        }
        // dump($rules);exit;
        return array(
          'success'       =>true,
          'mainFormItems' =>$mainFormItems,
          'sonFormItems'  =>array(),
          'rules'         =>$rules,
          'action'        =>$this->_url('Save'),
          'urlRemoveSon'  =>$this->_url('RemoveSonAjax'),
        );
    }

    /**
     * 创建入库的新编号
     * Time：2019/02/25 13:03:19
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function createNewCode(){
      $code = $this->_getNewCode($this->codePrev ,$this->_modelExample->tableName ,$this->_modelExample->codeField);
      return $code;
    }

    /**
     * @desc ：员工档案查询
     * Time：2017/07/31 15:45:28
     * @author li
    */
    function actionRight() {
        $this->authCheck($this->listFuckId);

        $searchItems = array(
            'dateRange' =>array(date('Y-m-d',mktime(0,0,0,date('m')-3,date('d'),date('Y'))),date('Y-m-d')),
            'productId' =>'',
            'purpose'   =>'',
            'proDesc'   =>'',
            'hzlId'     =>'',
            'kuweiId'   =>array(),
            'type'      =>array(),
            'guige'     =>'',
        );

        $smarty = & $this->_getView();

        $editButtons = array(
            array('text'=>'修改','type'=>'redirect','icon'=>'el-icon-edit','options'=>array(
                'url'            =>$this->_url('Edit').'&id={rukuId}',
                'disabledColumn' =>'__disabledEdit',
            )),
            array('text'=>'删除整个出库单数据','type'=>'remove','options'=>array(
                'url'            =>$this->_url('RemoveSonAjaxList'),
                'disabledColumn' =>'__disabledRemove',
            )),
            array('text'=>'打印标签','type'=>'redirect','icon'=>'el-icon-printer','options'=>array(
                'url'            =>$this->_url('Print').'&id={rukuId}',
                'disabledColumn' =>'__disabledPrint',
            )),
        );

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2TableNew();
        // dump($fileds);exit;
        // foreach ($fileds as & $fv) {
        //     $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        // }
        $arrFieldInfo = array_merge(
            array(
                "rukuCode"  =>array('text'=>"入库单号",'width'=>'','editButtons'=>$editButtons,'showButton'=>true),
                "rukuDate"  =>array('text'=>"入库日期",'width'=>'100'),
                "code"      =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'120'),
            )
            ,$fileds
            ,array(
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'100','forKeySearch'=>true),
                "type"      =>array('text'=>"样品类型",'width'=>'90'),
                "kindName"  =>array('text'=>"产品类别",'width'=>'90'),
                "cnt"       =>array('text'=>"数量",'width'=>'70'),
                "price"     =>array('text'=>"单价",'width'=>'70'),
                "gexing"    =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"     =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"     =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"       =>array('text'=>"后整理工艺",'width'=>'100'),
                // "code"      =>array('text'=>"条码",'width'=>'110','forKeySearch'=>true),
                "kuweiName" =>array('text'=>"库位",'width'=>'90'),
                "purpose"   =>array('text'=>"用途",'width'=>'90','forKeySearch'=>true),
                'preview'   =>array('text'=>"预览",'width'=>'70','type'=>'component','options'=>array('type'=>'tip-preview-image',)),
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                "reason"    =>array('text'=>"来源",'width'=>'100','forKeySearch'=>true),
                "creater"   =>array('text'=>"操作人",'width'=>'100'),
                "memo"      =>array('text'=>"备注",'width'=>'100'),
            )
        );
        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('actionLoadData', $this->_url('GetRows'));
        $smarty->assign('searchItems', $searchItems);
        $smarty->assign('colsForKey', array(
            array('text' =>'产品规格','col'=>'proKey'),
            array('text' =>'产品编号','col'=>'code'),
            array('text' =>'产品名称','col'=>'proName'),
            // array('text' =>'规格','col'=>'guige'),
            array('text' =>'格型','col'=>'gexing'),
            array('text' =>'组织','col'=>'zuzhi'),
            array('text' =>'花型颜色','col'=>'proDesc'),
            array('text' =>'来源','col'=>'reason'),
        ));

        $smarty->assign('addUrl',$this->_url('Add'));
        $smarty->assign('menuRightTop', array(
            // array('text'=>'新增入库','icon'=>'el-icon-plus','url'=>$this->_url('Add')),
            array('text'=>'新增入库','icon'=>'el-icon-plus','url'=>url('Sample_Ruku','RukuSimple')),
            array('text'=>'批量打印','name'=>'btnPrintList','icon'=>'el-icon-printer'),
            // array('text'=>'导入-入库记录','url'=>$this->_url('ImportRkData'),'icon'=>'el-icon-folder-checked')
        ));
        $smarty->assign('sonTpl','Sample/RukuSimple/TableList.js');
        $smarty->assign('multiSelect',true );
        $smarty->assign('actionExportAll', $this->_url('GetRows',array('exportExcel'=>1)));
        $smarty->display('Async/TableList.tpl');
    }

    // function actionSolveData(){
    //     set_time_limit(0);

    //     ob_end_clean();
    //     ob_implicit_flush(1);

    //     $rk = $this->_subModel->findAll();
    //     $modelProduct = FLEA::getSingleton("Model_Jichu_Product");
    //     $count = count($rk);
    //     $sql = "update sample_ruku2product a left join sample_kucun b on a.id = b.rukuId set a.code = '',b.code='',a.append=0 where b.rukuId = a.id";
    //     $res = $this->_modelExample->execute($sql);
    //     foreach ($rk as $k => & $v) {

    //         $v['code'] = $this->_modelExample->createNewCode($v,$codeNext);
    //         $pros = $modelProduct->find($v['productId']);
    //         //追加后缀的时候需要判断前缀是否在条码中且条码长度大于前缀
    //         $mark = strripos($v['code'],$pros['prefix']);
    //         $codeLength = strlen($v['code']);
    //         $proLength = strlen($pros['prefix']);
    //         if($mark >= 0 && $codeLength > $proLength){
    //             $last = strrpos($v['code'], '-');
    //             $v['append'] = substr($v['code'], $last+1);
    //         }else{
    //             $v['append'] = 0;
    //         }
    //         $result = $this->_subModel->save($v);
    //         if($result){
    //             echo ($k+1).":成功->",(round(($k+1)/$count*100 , 2)),"%<br/>";
    //         }else{
    //             echo "<font style='color:red;'>".($k+1).":失败</font>","<br/>";
    //         }
    //         unset($rk[$k]);
    //     }
    // }

    /**
     * @desc ：员工档案查询
     * Time：2017/07/31 15:45:28
     * @author li
    */
    function actionReportViewList() {
        $this->authCheck(0);
        $dateFrom = $_GET['dateFrom'] ? $_GET['dateFrom'] : date('Y-m-01');
        $dateTo = $_GET['dateTo'] ? $_GET['dateTo'] : date('Y-m-d');

        $searchItems = array(
            'dateRange' =>array($dateFrom, $dateTo),
            'barCode'   =>$_GET['code'].'',
            'purpose'   =>'',
            'proDesc'   =>$_GET['proDesc'].'',
            'productId' =>$_GET['productId'],
            'kuweiId'   =>array($_GET['kuweiId']),
            'type'      =>array($_GET['type']),
        );

        $smarty = & $this->_getView();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->fileds2Table();
        foreach ($fileds as & $fv) {
            $fv = array('text'=>$fv ,'width'=>(mb_strlen($fv,'utf8')*18 > 100 ? mb_strlen($fv,'utf8')*18 : 100));
        }
        $arrFieldInfo = array_merge(
            array(
                "rukuDate"  =>array('text'=>"入库日期",'width'=>'110'),
                "rukuCode"  =>array('text'=>"入库单号",'width'=>'120'),
                "purpose"   =>array('text'=>"用途",'width'=>'100','forKeySearch'=>true),
                "kindName"  =>array('text'=>"产品类别",'width'=>'100'),
                "code"      =>array('text'=>"产品编号",'width'=>'100'),
                "proName"   =>array('text'=>"产品名称",'width'=>'100'),
                "proDesc"   =>array('text'=>"花型颜色",'width'=>'140','forKeySearch'=>true),
                "type"      =>array('text'=>"样品类型",'width'=>'100'),
                "gexing"    =>array('text'=>"格型",'width'=>'90','forKeySearch'=>true),
                "zuzhi"     =>array('text'=>"组织",'width'=>'90','forKeySearch'=>true),
                // "tanli"     =>array('text'=>"弹力",'width'=>'90','forKeySearch'=>true),
                "hzl"       =>array('text'=>"后整理工艺",'width'=>'100'),
                // "code"      =>array('text'=>"条码",'width'=>'110','forKeySearch'=>true),
                "cnt"       =>array('text'=>"数量",'width'=>'70'),
                "kuweiName" =>array('text'=>"库位",'width'=>'100'),
            )
            ,$fileds
            ,array(
                'otherDesc' => array('text'=>'其他描述','width'=>'150','type'=>'html'),
                "creater"   =>array('text'=>"操作人",'width'=>'100'),
                "memoView"  =>array('text'=>"备注",'width'=>''),
            )
        );

        $smarty->assign('title', $this->kind.'查询');
        $smarty->assign('arr_field_info', $arrFieldInfo);
        $smarty->assign('action', $this->_url('GetRows'));
        $smarty->assign('searchItems', $searchItems);

        // $smarty->assign('addUrl',$this->_url('Add'));
        // $smarty->assign('menuRightTop', array(
        //     array('text'=>'新增(不关联制作单)','url'=>$this->_url('Add')),
        // ));
        // $smarty->assign('sonTpl',array(
        //     'Jichu/TableProductList.js'
        // ));
        $smarty->assign('ignoreSearchCache',true);
        $smarty->display('TableList_v1.1.tpl');
    }

    /**
     * 获取计划任务的数据
     * @author li
    */
    public function actionGetRows() {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array(
              'total'   =>0,
              'columns' =>array(),
              'rows'    =>array(),
            );
            echo json_encode($ret);exit;
        }
        FLEA::loadClass('TMIS_Common');

        $post = $this->axiosPost();
        $pagesize    = $post['pagesize'];
        $currentPage = $post['currentPage'];

        $keyField    = isset($post['colForKey']) ? $post['colForKey'] : 'key';
        //处理搜搜
        $post[$keyField] = $post['key'];
        if($keyField!='key') $post['key'] = '';

        $arr = $post;
        $sql="SELECT x.*,y.rukuDate,y.rukuCode,y.reason,y.creater,y.purpose,y.memo
              from sample_ruku2product x
              left join sample_ruku y on y.id=x.rukuId
              left join jichu_product p on p.id=x.productId
              where 1 ";

        if($arr['rukuCode']!='') {
            $sql.=" and y.rukuCode like '%{$arr['rukuCode']}%'";
        }
        if($arr['proKey']!=''){
            // $sql.=" and(
            //     p.filed1 like '%{$arr['proKey']}%'
            //     or p.filed2 like '%{$arr['proKey']}%'
            //     or p.filed3 like '%{$arr['proKey']}%'
            //     or p.filed4 like '%{$arr['proKey']}%'
            //     or p.filed5 like '%{$arr['proKey']}%'
            //     or p.filed6 like '%{$arr['proKey']}%'
            //     or p.filed7 like '%{$arr['proKey']}%'
            //     or p.filed8 like '%{$arr['proKey']}%'
            //     or p.filed9 like '%{$arr['proKey']}%'
            //     or p.filed10 like '%{$arr['proKey']}%')";
            $sql .= " and p.filed3 like '%{$arr['proKey']}%'";
        }
        if($arr['purpose']!='') {
            $sql.=" and y.purpose like '%{$arr['purpose']}%'";
        }
        if($arr['reason']!='') {
            $sql.=" and y.reason like '%{$arr['reason']}%'";
        }
        if($arr['type']) {
            foreach ($arr['type'] as & $a) {
                $a = "'{$a}'";
            }
            $type = join(',' ,$arr['type']);
            $sql.=" and x.type in ({$type})";
        }
        if($arr['proDesc']!='') {
            $sql.=" and x.proDesc like '%{$arr['proDesc']}%'";
        }
        if($arr['gexing']!='') {
            $sql.=" and x.gexing like '%{$arr['gexing']}%'";
        }
        if($arr['zuzhi']!='') {
            $sql.=" and x.zuzhi like '%{$arr['zuzhi']}%'";
        }
        // if($arr['tanli']!='') {
        //     $sql.=" and x.tanli like '%{$arr['tanli']}%'";
        // }
        if($arr['hzlId']!='') {
            $sql.=" and find_in_set({$arr['hzlId']} ,`hzlId`)";
        }
        if($arr['code']!='') {
            $sql.=" and x.code like '%{$arr['code']}%'";
        }
        if($arr['reason']!='') {
            $sql.=" and y.reason like '%{$arr['reason']}%'";
        }
        if($arr['proName']!='') {
            $sql.=" and p.proName like '%{$arr['proName']}%'";
        }
        if($arr['proCode']!='') {
            $sql.=" and p.proCode like '%{$arr['proCode']}%'";
        }
        if($arr['guige']!='') {
            $sql.=" and p.guige like '%{$arr['guige']}%'";
        }

        if($arr['productId']) {
            $sql.=" and x.productId = '{$arr['productId']}'";
        }
        if($arr['kuweiId']) {
            $kuweiId = join(',' ,$arr['kuweiId']);
            $sql.=" and x.kuweiId in ({$kuweiId})";
        }
        if($arr['dateRange']){
            list($datefrom ,$dateTo) = $arr['dateRange'];
            $sql .= " and y.rukuDate >= '{$datefrom}' and y.rukuDate <= '{$dateTo}'";
        }
        $sql .=" order by y.rukuDate desc,p.prefix,p.suffix,x.append desc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pagesize ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $modelProduct->filedValue2($v ,$tmp[0] ,$filedsSingle);
            $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'html','' ,$filedsDefault);

            $v['cnt'] = round($v['cnt'],6);

            $_tmp = $modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_tmp['kuweiName'];

            //图片预览
            if($v['imageId']){
                $sql = "SELECT * from jichu_image where id in({$v['imageId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                // $tmp = array_col_values($tmp,'path');
                foreach ($tmp as & $ii) {
                    $v['imageSrc'][] = array(
                        'path'=>TMIS_Common::_imageSrc($ii['path'])
                    );
                }
            }
            // 查找后整理工艺
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }
        }
        $ret = array(
          'total'   =>$pager->totalCount,
          'columns' =>array(),
          'rows'    =>$rowset,
        );
        echo json_encode($ret);exit;
    }

    /**
     * 新增
     * Time：
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionRukuSimple(){
        $kind = $this->_modelKind->findAll();
        foreach ($kind as $key => & $v) {
            $v['rukuUrl'] = $this->_url('Add',array('kindId'=>$v['id']));
        }

        $row = array(
            'kind'=>$kind,
        );
        // dump($row);exit;
        $smarty   = & $this->_getView();
        $smarty->assign('title', '样品入库');
        $smarty->assign('row', $row);
        $smarty->assign('sonTpl', 'Sample/RukuSimple/rukuSimple.js');
        $smarty->display('Sample/RukuSimple/rukuSimple.tpl');
    }

    /**
     * 新增
     * Time：2018/12/17 13:35:37
     * @author li
    */
    function actionAdd() {
        $this->authCheck($this->editFuckId);
        $Arr = array('kindId'=>$_GET['kindId']);
        $this->_edit($Arr);
    }

    function beforeDisplay(& $smarty){
        $smarty->assign('sonTpl','Sample/RukuSimple/Add.js');
        // dump($smarty);exit;
    }

    function actionEdit(){
        $this->authCheck($this->editFuckId);

        // 单条修改
        $arr = $this->_modelExample->find($_GET['id']);
        $row = $arr;
        //查产品种类
        foreach ($row['Products'] as $k => & $v) {
            $sql = "SELECT kindId from jichu_product where id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['kindId']   = $tmp[0]['kindId'];
            $row['kindId'] = $tmp[0]['kindId'];
        }
        // dump($row);exit;
        $this->_edit($row);
    }

    function _edit($Arr = array() ,$fromAction) {
        $Arr['fromAction'] = $fromAction;

        //处理档案
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelPro = FLEA::getSingleton('Model_Jichu_Product');
        $modelProKind = FLEA::getSingleton('Model_Jichu_ProKind');
        foreach ($Arr['Products'] as & $v) {
            if($v['kuweiId']){
                $tmp = $modelKuwei->find($v['kuweiId']);
                $v['kuweiName'] = $tmp['kuweiName'];
            }

            if($v['imageId']){
                //查找图片路径
                $sql = "SELECT * from jichu_image where id in ({$v['imageId']})";
                $images = $this->_modelExample->findBySql($sql);
                foreach ($images as & $img) {
                    $v['image2phone'][] = array(
                        'name'    =>'img_'.$v['id'].'_'.$img['id'],
                        'imageId' =>$img['id'],
                        'url'     =>$img['path'],
                    );
                }
                $v['picDesc'] = count($v['image2phone']) .'张';
            }else{
                $v['image2phone'] = array();
            }

            $v['hzlId'] = $v['hzlId'] ? explode(',',$v['hzlId']) : array();
        }



        //查找产品档案的信息
        $fileds = $modelProKind->getFileds($Arr['kindId'],'');
        $filedArr = array_merge((array)$fileds['single'],(array)$fileds['default']);
        if($Arr['Products'][0]['productId']){
            $sql = "select x.*,y.id as kindId from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$Arr['Products'][0]['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($filedArr as $kk => & $vv) {
                $Arr[$vv['filed']] = $tmp[0][$vv['filed']];
            }
            $Arr['proCode'] = $tmp[0]['proCode'].'';
            $Arr['proName'] = $tmp[0]['proName'].'';
        }



        $pros = $Arr['Products'][0];
        // 平铺出明细数据
        $Arr['sonId']       = $pros['id'];
        // $Arr['kindId']      = $tmp[0]['kindId'];
        $Arr['productId']   = $pros['productId'];
        $Arr['type']        = $pros['type'].'';
        $Arr['cnt']         = $pros['cnt'];
        $Arr['kuweiId']     = $pros['kuweiId'];
        $Arr['code']        = $pros['code'];
        $Arr['image2phone'] = $pros['image2phone'] ? $pros['image2phone'] : array();
        $Arr['imageId']     = $pros['imageId'];
        $Arr['kuweiName']   = $pros['kuweiName'];
        $Arr['gexing']      = $pros['gexing'].'';
        $Arr['zuzhi']       = $pros['zuzhi'].'';
        $Arr['price']       = $pros['price'].'';
        // $Arr['tanli']       = $pros['tanli'];
        $Arr['hzlId']       = $pros['hzlId'] ? $pros['hzlId'] : array();
        $Arr['productDesc'] = $pros['productDesc'];
        $Arr['proDesc']     = $pros['proDesc'];

        // dump($Arr);exit;

        $smarty = & $this->_getView();
        $smarty->assign('title','基本信息');
        $smarty->assign('row',$Arr);
        $smarty->assign('sonTpl','Sample/RukuSimple/Add.js');
        $smarty->assign('formItems',$this->_getMainFormItems(array('kindId'=>$Arr['kindId']) , $filed));
        $smarty->assign('jichuField',$filedArr);
        $this->beforeDisplay($smarty);
        $smarty->display('Async/MainSonForm.tpl');
    }





    //保存数据
    function actionSave(){
        //保存的时候分为两种情况
        //1.新增入库的时候不选产品档案,如果所有信息都对应上了基础档案里的某个产品的话就直接取出该id,否则的话就是新建一个产品档案
        //2.新增入库和修改入库记录时都选择了产品档案的话,最简单的情况就是所有产品档案的属性都没有改动,是改动的入库信息,这个就是直接保存
        //但是如果是有改动了产品信息的话,需要弹窗询问客户是要重新新增一个产品档案还是要更改所有和该产品相关的出入库记录,从而做对应的操作
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array('msg'=>'登录权限过期','success'=>false);
            echo json_encode($ret);exit;
        }
        $post = $this->axiosPost();
        //先获取系统参数设置中设置的产品编号前缀
        // $modelConfig = FLEA::getSingleton("Model_Acm_SetParamters");
        // $Config = $modelConfig->findAll();
        // foreach ($Config as $k => & $v) {
        //     if($v['item']=='prefix'){
        //         $proPrev = $v['value'];
        //     }
        // }
        $sys = $this->getSysSet();
        $this->proPrev = $sys['prefix'] ? $sys['prefix'] : $this->proPrev;
        $post['proCode'] = $post['proCode'] ? $post['proCode'] : $this->CreateProCode($this->proPrev,'','jichu_product','proCode');
        //限制编号只能用数字加中英文
        $match = "/^[a-zA-Z0-9-_\/]*$/";
        if(!preg_match($match,$post['proCode'])){
            $ret = array('msg'=>'产品编号含有数字英文以外的字符','success'=>false);
            echo json_encode($ret);exit;
        }else{
            if(strlen($post['proCode']) < 5 || strlen($post['proCode']) > 20){
                $ret = array('msg'=>'产品编号字符长度5~20','success'=>false);
                echo json_encode($ret);exit;
            }
        }
        if(!$post['rukuCode']){
            $post['rukuCode'] = $this->createNewCode();
        }
        //处理基础档案
        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $pro = array();
        $pro['proCode'] = $post['proCode'];
        $pro['proName'] = $post['proName'];
        $pro['kindId'] = $post['kindId'];
        $product = $modelProduct->find($post['productId']);
        $proPrev = substr($product['proCode'], 0,6);
        $fileds = $this->_modelKind->getFileds($post['kindId'] ,'all');
        foreach ($fileds as $key => & $v) {
            $pro[$v['filed']] = $post[$v['filed']].'';
        }
        if($post['isProductUpdate']){
            if($post['isProductUpdate'] == 'add'){
                $pro['proCode'] = $this->CreateProCode($proPrev,'','jichu_product','proCode');
                $pro['prefix'] = $pro['proCode'];
                $pro['suffix'] = 0;
                $productId = $modelProduct->save($pro);
            }else{
                $pro['id'] = $post['productId'];
                $res = $modelProduct->save($pro);
                if($res){
                    $productId = $pro['id'];
                }
            }
        }else{
            //第一种情况
            if(empty($post['productId'])){
                //如果有基础信息完全相同的产品获取它的id,否则就是新增产品
                // $sql = "SELECT id from jichu_product where proName = '{$post['proName']}' and kindId = '{$post['kindId']}'";
                $condition = array();
                $condition[] = array('proName',$post['proName'],'=');
                $condition[] = array('kindId',$post['kindId'],'=');
                foreach ($fileds as $key => & $va) {
                    $condition[] = array("{$va['filed']}","{$pro[$va['filed']]}",'=');
                }
                $product = $modelProduct->find($condition);
                if($product){
                    $productId = $product['id'];
                }else{
                    $products = $modelProduct->find(array('proCode'=>$pro['proCode']));
                    if($products['suffix']==0){
                        $pro['prefix'] = $pro['proCode'];
                    }else{
                        $pro['prefix'] = $products['prefix'];
                    }
                    $productId = $modelProduct->save($pro);
                }
            }else{
                //如果有基础信息完全相同的产品获取它的id,否则就是新增产品
                // $sql = "SELECT id from jichu_product where proName = '{$post['proName']}' and kindId = '{$post['kindId']}'";
                $condition = array();
                $condition[] = array('proName',$post['proName'],'=');
                $condition[] = array('kindId',$post['kindId'],'=');
                $condition[] = array('id',$post['productId'],'=');
                foreach ($fileds as $key => & $va) {
                    $condition[] = array("{$va['filed']}","{$pro[$va['filed']]}",'=');
                }
                $product = $modelProduct->find($condition);
                if($product){
                    $productId = $product['id'];
                }else{
                    $ret = array('msg'=>'','success'=>true,'dialogIsUpdate'=>true);
                    echo json_encode($ret);exit;
                }
            }
        }
        !$post['creater'] && $post['creater'] = $_SESSION['REALNAME'];
        // 用于排序
        sort($post['hzlId']);
        // dump($post['hzlId']);exit;
        foreach ($post['hzlId'] as $k => & $va) {
            if($va == ''){
                unset($post['hzlId'][$k]);continue;
            }
        }
        $post['hzlId'] = array_values($post['hzlId']);
        unset($post['Products']);
        $post['Products'][] = array(
            'id'        =>$post['sonId'],
            'productId' =>$productId,
            'cnt'       =>$post['cnt'],
            'type'      =>strval($post['type']),
            'proDesc'   =>strval($post['proDesc']),
            'kuweiId'   =>$post['kuweiId'],
            'price'     =>$post['price'],
            'code'      =>strval($post['code']),
            'imageId'   =>join(',', array_col_values($post['image2phone'],'imageId')),
            'gexing'    =>strval($post['gexing']),
            'zuzhi'     =>strval($post['zuzhi']),
            // 'tanli'     =>strval($post['tanli']),
            'hzlId'     =>$post['hzlId'] ? join(',' ,$post['hzlId']) : '',
        );
        // dump($post);exit;

        $codeNext = 0;
        foreach ($post['Products'] as $key => &$v) {
            //处理条码的数据:验证并保证唯一，相同产品条码一致
            // 1.判断如果有条码，是否合法字符串
            $v['code'] = trim($v['code']);
            if($v['code']!=''){
                $match = "/^[a-zA-Z0-9-_\/]*$/";
                if(!preg_match($match,$v['code'])){
                    $ret = array('msg'=>'条码含有数字英文以外的字符','success'=>false);
                    echo json_encode($ret);exit;
                }else{
                    if(strlen($v['code']) < 6 || strlen($v['code']) > 30){
                        $ret = array('msg'=>'条码字符长度6~30','success'=>false);
                        echo json_encode($ret);exit;
                    }
                }
            }

            //条码规则：相同productId和产品编号，类型，条码保证一致
            //先查找该样品信息是否已经存在历史条码，如果已经存在，则直接使用历史条码
            $sql = "SELECT code from sample_ruku2product where productId='{$v['productId']}' and id<>'{$v['id']}' and proDesc='{$v['proDesc']}' and type='{$v['type']}' and gexing='{$v['gexing']}' and zuzhi = '{$v['zuzhi']}' and hzlId='{$v['hzlId']}' limit 0,1";
            $res = $this->_subModel->findBySql($sql);
            $_code = strval($res[0]['code']);
            //生成条码
            if($v['code'] == ''){
                if($_code){
                    $v['code'] = $_code;
                }else{
                    $v['code'] = $this->_modelExample->createNewCode($v,$codeNext);
                    $pros = $modelProduct->find($v['productId']);
                    //追加后缀的时候需要判断前缀是否在条码中且条码长度大于前缀
                    $mark = strripos($v['code'],$pros['prefix']);
                    $codeLength = strlen($v['code']);
                    $proLength = strlen($pros['prefix']);
                    if($mark >= 0 && $codeLength > $proLength){
                        $last = strrpos($v['code'], '-');
                        $v['append'] = substr($v['code'], $last+1);
                    }else{
                        $v['append'] = 0;
                    }
                    $codeNext++;
                }
            }else{
                // 如果填写的条码和历史条码不一致，则需要提醒错误
                if($_code && $v['code']<>$_code){
                    $ret = array('msg'=>'该规格类型样品有产品条码('.$_code.')，留空系统自动使用','success'=>false);
                    echo json_encode($ret);exit;
                }
                //查找条码是否重复:相同的产品和类型允许重复，否则不允许
                $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$v['code']}' and (productId<>'{$v['productId']}' or proDesc<>'{$v['proDesc']}' or type<>'{$v['type']}' or gexing<>'{$v['gexing']}' and zuzhi <> '{$v['zuzhi']}' or hzlId<>'{$v['hzlId']}') and id<>'{$v['id']}'";
                // dump($sql);exit;
                $res = $this->_modelExample->findBySql($sql);
                if($res[0]['cnt'] > 0){
                    $ret = array('msg'=>'条码已经被其他产品使用','success'=>false);
                    echo json_encode($ret);exit;
                }
            }
        }

        //数据保存
        // $productId = $modelProduct->save();
        // dump($post);exit;
        $result = $this->_modelExample->save($post);
        if($result){
            $ret = array(
                'success'   =>true,
                'msg'       =>'操作成功',
                'targetUrl' =>$this->_url($post['fromAction'] ? $post['fromAction'] : 'Right'),
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'操作失败',
            );
        }

        echo json_encode($ret);exit;
    }

    function CreateProCode($head,$next,$tblName,$fieldName){
        $m = & FLEA::getSingleton('Model_Acm_User');
        $m->force_master = true;

        $sql = "select {$fieldName} from {$tblName} where {$fieldName} like '{$head}{$next}_____' order by {$fieldName} desc limit 0,1";
        $_r = $m->findBySql($sql);
        $row = $_r[0];
        $init = $head.$next.'00001';
        if(empty($row[$fieldName])) return $init;
        if($init>$row[$fieldName]) return $init;
        // dump($init);exit;
        //自增1
        $max = substr($row[$fieldName],-5);
        $pre = substr($row[$fieldName],0,-5);

        return $pre .substr(100001+$max,1);
    }

    function CreateNewProCode($proCode,$tblName,$fieldName){
        $m = & FLEA::getSingleton('Model_Acm_User');
        $m->force_master = true;
        $modelProduct = FLEA::getSingleton("Model_Jichu_Product");
        $product = $modelProduct->find(array('proCode'=>$proCode));
        $pre = $product['prefix'].'-';
        $sql = "select {$fieldName},suffix from {$tblName} where {$fieldName} like '{$pre}%' order by suffix desc limit 0,1";
        $_r = $m->findBySql($sql);
        $row = $_r[0];
        if(empty($row[$fieldName]) || $init > $row[$fieldName]){
            $max = 0;
        }else{
            //自增1
            $max = $row['suffix'];
        }
        // dump($init);exit;
        //自增1
        // $max = substr($row[$fieldName],-3);
        // $pre = substr($row[$fieldName],0,-4);
        return $pre .($max+1);
        // return $pre .$break.substr(1001+$max,1);
    }

    /**
     * 档案保存
     * Time：2017/07/31 15:48:32
     * @author li
    */
    function actionSaveOld() {
        $auth = $this->authCheck(0 ,true);
        if(!$auth){
            $ret = array('msg'=>'登录权限过期','success'=>false);
            echo json_encode($ret);exit;
        }
        $post = $this->axiosPost();
        if(!$post['rukuCode']){
            $post['rukuCode'] = $this->createNewCode();
        }
        !$post['creater'] && $post['creater'] = $_SESSION['REALNAME'];

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $codeNext = 0;
        foreach ($post['Products'] as $key => &$v) {
            //如果没有数量或者材料Id,则跳过
            if(!$v['productId']){
                unset($post['Products'][$key]);
            }
            if(!$v['kuweiId']){
                $ret = array('msg'=>'第'.($key+1).'行有误，请确认选择库位','success'=>false);
                echo json_encode($ret);exit;
            }
            if(!$v['cnt']){
                $ret = array('msg'=>'第'.($key+1).'行有误，请确认填写数量','success'=>false);
                echo json_encode($ret);exit;
            }

            //处理条码的数据:验证并保证唯一，相同产品条码一致
            // 1.判断如果有条码，是否合法字符串
            $v['code'] = trim($v['code']);
            if($v['code']!=''){
                $match = "/^[a-zA-Z0-9-_\/]*$/";
                if(!preg_match($match,$v['code'])){
                    $ret = array('msg'=>'第'.($key+1).'行有误，条码含有数字英文以外的字符','success'=>false);
                    echo json_encode($ret);exit;
                }else{
                    if(strlen($v['code']) < 6 || strlen($v['code']) > 30){
                        $ret = array('msg'=>'第'.($key+1).'行有误，条码字符长度6~30','success'=>false);
                        echo json_encode($ret);exit;
                    }
                }
            }

            //条码规则：相同productId和产品编号，类型，条码保证一致
            //先查找该样品信息是否已经存在历史条码，如果已经存在，则直接使用历史条码
            $sql = "SELECT code from sample_ruku2product where productId='{$v['productId']}' and id<>'{$v['id']}' and proDesc='{$v['proDesc']}' and type='{$v['type']}' limit 0,1";
            $res = $this->_subModel->findBySql($sql);
            $_code = strval($res[0]['code']);

            //生成条码
            if($v['code'] == ''){
                if($_code){
                    $v['code'] = $_code;
                }else{
                    $v['code'] = $this->_modelExample->createNewCode($v,$codeNext);
                    $codeNext++;
                }
            }else{
                // 如果填写的条码和历史条码不一致，则需要提醒错误
                if($_code && $v['code']<>$_code){
                    $ret = array('msg'=>'第'.($key+1).'行有误，该规格类型样品有产品条码('.$_code.')，留空系统自动使用','success'=>false);
                    echo json_encode($ret);exit;
                }
                //查找条码是否重复:相同的产品和类型允许重复，否则不允许
                $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$v['code']}' and (productId<>'{$v['productId']}' or proDesc<>'{$v['proDesc']}' or type<>'{$v['type']}' ) and id<>'{$v['id']}'";
                $res = $this->_modelExample->findBySql($sql);
                if($res[0]['cnt'] > 0){
                    $ret = array('msg'=>'第'.($key+1).'行有误，条码已经被其他产品使用','success'=>false);
                    echo json_encode($ret);exit;
                }
            }

            //处理图片上传
            if(count($v['image2phone']) > 0){
                $v['imageId'] = join(',', array_col_values($v['image2phone'],'imageId'));
            }
        }

        if(!$post['Products']){
            $ret = array('msg'=>'无有效明细信息','success'=>false);
            echo json_encode($ret);exit;
        }
        // dump($post);exit;
        //数据保存
        $result = $this->_modelExample->save($post);
        if($result){
            $ret = array(
                'success'   =>true,
                'msg'       =>'操作成功',
                'targetUrl' =>$this->_url($post['fromAction'] ? $post['fromAction'] : 'Right'),
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'操作失败',
            );
        }

        echo json_encode($ret);exit;
    }

    function actionRemoveSonAjaxList(){
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);
        $id = intval($_POST['row']['id']);

        $row = $this->_subModel->find($id);
        if($row['rukuId']){
            $oldInfo = $this->_modelExample->find($row['rukuId']);
            $res = $this->_modelExample->removeByPkv($row['rukuId']);
        }

        if($res){
            $imageIds = array_col_values($oldInfo['Products'],'imageId');
            $imageIds = join(',',$imageIds);
            if($imageIds){
                $imgClass = FLEA::getSingleton('Controller_Jichu_Image');
                $image = explode(',', $imageIds);
                foreach ($image as & $img) {
                    $imgClass->_removeImg($img);
                }
            }

            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    function actionRemoveAjax() {
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);
        $id = intval($_POST['row']['id']);

        $oldInfo = $this->_modelExample->find($id);
        $res = $this->_modelExample->removeByPkv($id);

        if($res){
            $imageIds = array_col_values($oldInfo['Products'],'imageId');
            $imageIds = join(',',$imageIds);
            if($imageIds){
                $imgClass = FLEA::getSingleton('Controller_Jichu_Image');
                $image = explode(',', $imageIds);
                foreach ($image as & $img) {
                    $imgClass->_removeImg($img);
                }
            }
            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    function actionRemoveSonAjax() {
        $requestParam = file_get_contents('php://input');
        $_POST = json_decode($requestParam,true);
        $id = intval($_POST['id']);

        $oldInfo = $this->_subModel->find($id);
        $res = $this->_subModel->removeByPkv($id);

        if($res){
            //同时触发删除图片基础库的数据，物理删除图片文件
            if($oldInfo['imageId']){
                $imgClass = FLEA::getSingleton('Controller_Jichu_Image');
                $image = explode(',', $oldInfo['imageId']);
                foreach ($image as & $img) {
                    $imgClass->_removeImg($img);
                }
            }

            $ret = array(
                'success' =>true,
                'msg'     =>'删除成功',
            );
        }else{
            $ret = array(
                'success' =>false,
                'msg'     =>'删除失败',
            );
        }
        echo json_encode($ret);exit;
    }

    /**
     * 打印标签
     * Time：2019/10/24 17:04:44
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionPrint(){
        //每个产品分类的标签配置不一样，所以先获取配置，如果没有配置需要提醒需要先配置
        $_modelKind  = FLEA::getSingleton('Model_Jichu_ProKind');
        $_modelPro   = FLEA::getSingleton('Model_Jichu_Product');
        $_modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');

        $rukuId = $_GET['id'] ? $_GET['id'] : '-1';
        $sql = "SELECT x.*,y.rukuDate as `date`,y.memo as remark,y.reason,y.purpose
            from sample_ruku2product x
            left join sample_ruku y on x.rukuId=y.id
            where y.id in({$rukuId})";
        $rukuInfo = $this->_modelExample->findBySql($sql);

        $allKind = $_modelKind->findAll();
        $sys['compName'] = $this->getCompName();
        //标题映射
        $titleConfig = array(
            'chinese'           =>'title',
            'english'           =>'titleEng',
            'chineseAndEnglish' =>'title,titleEng',
        );

        //花型颜色的标题
        $_tR = array('proDesc','gexing','zuzhi','hzl','kuweiName','remark','date','code');

        $_tP = array('proName','proCode');

        $_detialTitle = array_merge($_tR ,$_tP);

        //处理配置的信息，把需要打印的配置整理成下面需要的格式
        $_config = array();
        foreach ($allKind as $key => & $v) {
            $v['fields'] = $v['extendAttr'] ? json_decode($v['extendAttr'] ,true) : array();
            foreach ($v['PrintCfg'] as $k => & $va) {
                $v['print'][] = $va ? json_decode($va['printConfig'] ,true) : array();
                $v['print'][$k]['id'] = $va['id'];
                $v['print'][$k]['isDefault'] = $va['isDefault'];
            }
            $_config[$v['id']] = $v['print'];
        }

        //遍历产品信息，循环获取需要打印的标签有哪些，打印页面还要确认打印的数量
        $printPage = array();
        foreach ($rukuInfo as $key => & $v) {
            //处理每个产品需要打印的格式和排版
            $_product = $_modelPro->find($v['productId']);
            $v['Product'] = $_product;
            $_kuwei = $_modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_kuwei['kuweiName'];

            // 查找后整理
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }

            //如果没有配置打印，则显示无配置
            if(!isset($_config[$_product['kindId']])){
                $v['Print'] = array(
                    // 'error'=>'该分类未配置标签打印格式'
                );
                continue;
            }

            //把配置中的信息放到数据中
            $v['Print'] = $_config[$_product['kindId']];

            // //把需要展示的value字段找到
            foreach ($v['Print'] as $k => & $va) {
                foreach ($va['fileds'] as & $p) {
                    if(in_array($p, $_tR)){
                        $va['objectData'][$p] = strval($v[$p]).'';
                    }else{
                        $va['objectData'][$p] = $_product[$p].'';
                    }
                    $va['objectData']['code'] = $v['code'];
                }
                $va['objectData']['proCode'] = $v['code'];
            }
        }
        // dump($rukuInfo);exit;
        //打印标签
        $smarty = & $this->_getView();
        $smarty->assign('row',$rukuInfo);
        $smarty->assign('sys',$sys);
        $smarty->display('Sample/PrintCode.tpl');
    }

    /**
     * 打印标签
     * Time：2019/10/24 17:04:44
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionPrintAoEqinfo(){
        //每个产品分类的标签配置不一样，所以先获取配置，如果没有配置需要提醒需要先配置
        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $_modelPro = FLEA::getSingleton('Model_Jichu_Product');
        $_modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $rukuId = intval($_GET['id']);
        if(!$rukuId){
            echo "error params";exit;
        }
        $rukuInfo = $this->_modelExample->find($rukuId);
        $allKind = $_modelKind->findAll();

        //标题映射
        $titleConfig = array(
            'chinese'           =>'title',
            'english'           =>'titleEng',
            'chineseAndEnglish' =>'title,titleEng',
        );

        //标题映射
        $titleConfig = array(
            'chinese'           =>'title',
            'english'           =>'titleEng',
            'chineseAndEnglish' =>'title,titleEng',
        );

        //花型颜色的标题
        $_tR = array(
            'proDesc'=>array(
                'chinese'           =>'颜色',
                'english'           =>'Detail',
                'chineseAndEnglish' =>'颜色/Detail',
            ),
            'gexing'=>array(
                'chinese'           =>'格型',
                'english'           =>'Pattern',
                'chineseAndEnglish' =>'格型/Pattern',
            ),
            'zuzhi'=>array(
                'chinese'           =>'组织',
                'english'           =>'Construction',
                'chineseAndEnglish' =>'组织/Construction',
            ),
            'hzl'=>array(
                'chinese'           =>'后整理',
                'english'           =>'Finish',
                'chineseAndEnglish' =>'后整理/Finish',
            ),
            'kuweiName'=>array(
                'chinese'           =>'库位',
                'english'           =>'Location',
                'chineseAndEnglish' =>'库位/Location',
            ),
        );

        $_tP = array(
            'proName'=>array(
                'chinese'           =>'名称',
                'english'           =>'Name',
                'chineseAndEnglish' =>'名称/Name',
            ),
            'proCode'=>array(
                'chinese'           =>'编号',
                'english'           =>'No.',
                'chineseAndEnglish' =>'编号/No.',
            ),
        );

        $_detialTitle = array_merge($_tR ,$_tP);

        //处理配置的信息，把需要打印的配置整理成下面需要的格式
        $_config = array();
        foreach ($allKind as $key => & $v) {
            $v['fields'] = $v['extendAttr'] ? json_decode($v['extendAttr'] ,true) : array();
            $v['print'] = $v['printConfig'] ? json_decode($v['printConfig'] ,true) : array();
            $sys['logo'] = $v['print']['logo'][0];
            // dump($v);exit;
            //先确认标题显示的内容
            $show = array();
            $_tTmp = explode(',' ,$titleConfig[$v['print']['language']]);
            // dump($v);
            //先给标题加个中英文的
            if(!$v['print']){
                continue;
            }
            foreach ($v['fields'] as & $f) {
                $tmp = array();
                $tmp[] = $f['title'];
                $f['titleEng'] && $tmp[] = $f['titleEng'];
                $f['chinese'] = $f['title'];
                $f['english'] = $f['titleEng'] ? $f['titleEng'] : '未配置';
                $f['chineseAndEnglish'] = join('/' ,$tmp);
                // dump($f);
                //开始处理配置中的信息
                foreach($v['print']['fileds'] as & $f2) {
                    //花型颜色的标题
                    if(array_key_exists(trim($f2) ,$_detialTitle)){
                        $tmp = array(
                            'filed'=>$f2,
                            'title'=>$_detialTitle[trim($f2)][$v['print']['language']],
                        );
                        $f2 = $tmp;
                    }

                    if(trim($f2) == trim($f['filed'])){
                        $tmp = array(
                            'filed'=>$f['filed'],
                            'title'=>$f[$v['print']['language']],
                        );
                        $f2 = $tmp;
                    }
                }
                // dump($v['print']);
            }

            $_config[$v['id']] = $v['print'];
        }
        // dump($_config);

        //遍历产品信息，循环获取需要打印的标签有哪些，打印页面还要确认打印的数量
        $printPage = array();
        foreach ($rukuInfo['Products'] as $key => & $v) {
            //处理每个产品需要打印的格式和排版
            $_product = $_modelPro->find($v['productId']);
            $v['Product'] = $_product;

            $_kuwei = $_modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_kuwei['kuweiName'];

            // 查找后整理
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }

            //如果没有配置打印，则显示无配置
            if(!isset($_config[$_product['kindId']])){
                $v['Print'] = array(
                    'error'=>'该分类未配置标签打印格式'
                );
                continue;
            }

            //把配置中的信息放到数据中
            $v['Print'] = $_config[$_product['kindId']];
            //把需要展示的value字段找到
            foreach ($v['Print']['fileds'] as & $p) {
                if(isset($_tR[$p['filed']])){
                    $p['value'] = strval($v[$p['filed']]);
                }else{
                    $p['value'] = $_product[$p['filed']];
                }
            }
        }

        if($sys['logo']['imageId']){
            $sql = "SELECT * from jichu_image where id='{$sys['logo']['imageId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $sys['logo'] = $tmp[0];

            // logo显示默认是10mm，所以要计算出宽度缩放后的结果，用于计算偏右的开始布局位置
            $sys['logo']['hs'] = 10;
            $sys['logo']['ws'] = $sys['logo']['width'] * ($sys['logo']['hs']/$sys['logo']['height']);
        }

        // dump($rukuInfo);exit;
        $sys['compName'] = $this->getCompName();
        $_sys = $this->getSysSet();
        $sys['print_id_clodop'] = $_sys['print_id_clodop'];
        //打印标签
        $smarty = & $this->_getView();
        $smarty->assign('row',$rukuInfo);
        $smarty->assign('sys',$sys);
        $smarty->assign('print_id_clodop',$sys['print_id_clodop']);
        $smarty->display('Sample/PrintAo.tpl');
    }


    /**
     * 导出文档数据
     * Time：2019/12/19 17:29:07
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionImportFile(){
        $arr = array();

        //获取分类信息

        // $config = array(
        //     'proCode' =>'(英文和数组且长度5~20)',
        //     'code'    =>'条码(英文和数组且长度6~30)',
        // );


        $formParams = $this->buildHtmlImportantFile($kind ,$content);
        foreach ($formParams['formItems'] as & $v) {
            $arr[$v['name']] = $v['value'];
        }

        $col = $this->importCol;
        $col['errorMsg'] = '错误提示';


        $arrFieldInfo = array(
            "kindName"     =>"产品类别",
            "proCode"      =>"产品编号",
            "proName"      =>"产品名称",
            "isSampleText" =>"是否上架",
        );
        $fileds = $this->_modelKind->getFiledsKeyValueWidth($initKindid ,'all');
        foreach ($fileds as $key => & $v) {
            $arrFieldInfo[$key] = $v['text'];
        }
        $arrFieldInfo['memo'] = "备注";

        $smarty = & $this->_getView();
        $smarty->assign('formItems',$formParams['formItems']);
        $smarty->assign('rules',$formParams['rules']);
        $smarty->assign('title',"入库记录导入数据");
        $smarty->assign('row',$arr);
        $smarty->assign('importCol',$col);
        $smarty->assign('arrFieldInfo',$arrFieldInfo);
        $smarty->assign('action',$this->_url('ConfirmData'));
        $smarty->assign('actionConfirm',$this->_url('SaveConfirmData'));
        $smarty->display('Sample/ImportantData.tpl');
    }


    /**
     * 角色html配置form
     * Time：2018/12/13 15:49:40
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    public function buildHtmlImportantFile($kind ,$content) {
        $params = array();
        $params['formItems'] = array(
            array(
                'type'       =>'comp-file',
                'name'       =>'filePath',
                'title'      =>'上传样品入库',
                'buttonText' =>'开始上传附件',
                'action'     =>$this->_url('ImportFileData'),//上传地址
                'accept'     =>'.csv,.xls,.xlsx',//接受上传的文件类型
                'limit'      =>1,//最大允许上传个数
                'value'      =>'',
            ),
        );

        $params['rules'] = array(
            'filePath'=>array(
                array(
                    'required'=>true,
                    'message'=>'必须上传附件',
                )
            )
        );

        return $params;
    }

    /**
     * 接收文档
     * Time：2019/10/30 14:37:53
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionImportFileData(){
        $file = $_FILES['filePath'];
        $pathinfo = pathinfo($file['name']);
        // dump($pathinfo);
        if(strtolower($pathinfo['extension']) != 'csv' && strtolower($pathinfo['extension']) != 'xlsx' && strtolower($pathinfo['extension']) != 'xls'){
            $ret = array('msg'=>'文件类型必须为CSV,XLSX,XLS文件','success'=>false);
            echo json_encode($ret);exit;
        }

        $path = "upload/files/";
        $tmpname = $path.uniqid().rand(10000,99999).'.'.strtolower($pathinfo['extension']);
        move_uploaded_file($file['tmp_name'] ,$tmpname);

        $readData = $this->_readExcel($tmpname);
        $firstHead = $readData[0]; //表头
        foreach ($firstHead as $k => &$v) {
            $head[] = array('text'=>$v,'index'=>$k);
        }
        $ret = array('msg'=>'完成上传','success'=>true,'imgPath'=>$tmpname,'msg'=>'请查看数据并确认后操作','data'=>$head);
        echo json_encode($ret);exit;
    }

    /**
     * 确认数据
     * Time：2019/10/30 15:09:44
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function actionConfirmData(){
        $post = $this->axiosPost();
        // dump($post);exit;
        if(!$post['filePath']){
            $ret = array('success'=>false,'msg'=>'还没有上传文件');
            echo json_encode($ret);exit;
        }

        //开始上传数据
        $_data = array();
        foreach ($post['filePath'] as & $v) {
            if(!$v['url'] || !file_exists($v['url'])){
                continue;
            }
            //开始逐行读取数据
            $data = $this->handleData($v['url']);

            $_data = array_merge($_data,$data);
        }

        // dump($_data);exit;

        $v['url'] && @unlink(iconv('UTF-8','gb2312',$v['url']));
        $fail = array_sum(array_col_values($_data ,'fail'));
        $ret = array('gridData'=>$_data,'success'=>(count($_data) - $fail),'fail'=>$fail,'msg'=>'请查看数据并确认后操作');
        echo json_encode($ret);exit;

    }

    /**
   * 按行读取文件
   * @param string $filename
   */
  function readFileByLine($filename ,$params){
        $fh = fopen($filename, 'r');
        $_data = array();
        $i = 0;
        //导入的列配置
        $params['filed'] = $this->importCol;
        //全局做个条码，如果相同的产品条码不一致，需要提醒
        $codes = array();
        $_modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');

        while (! feof($fh)) {
          $line = fgets($fh);
          if($line){
            $i++;
            if($i == 1) continue;
            $tmp = explode(',', $line);

            $data = array();
            $data['fail'] = 0;
            $index = 0;
            foreach ($params['filed'] as $key => & $v) {
                $data[$key] = trim(iconv('GB2312', 'UTF-8', $tmp[$index])).'';
                $index++;
            }

            // $t = array_filter($data);
            // dump($data);
            if(!$data['proCode']){
                $data['error'][] = '无产品编号,该编号必须存在';
                $data['fail'] = 1;
                // continue;
            }

            //限制编号只能用数字加中英文
            $match = "/^[a-zA-Z0-9-_\/]*$/";
            if(!preg_match($match,$data['proCode'])){
                $data['error'][] = '编号含有数字英文以外的字符';
                $data['fail'] = 1;
                // continue;
            }else if(strlen($data['proCode']) < 5 || strlen($data['proCode']) > 20){
                $data['fail'] = 1;
                $data['error'][] = "产品编号字符长度不符合5~20";
                // continue;
            }

            //符合条件的产品编号，需要找到是否存在于档案中，如果不存在，则需要提示错误
            $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
            $product = $modelProduct->find(array('proCode'=>$data['proCode']));
            if(!$product['id']){
                $data['fail'] = 1;
                $data['error'][] = "产品在基础档案中不存在，请完善";
                // continue;
            }

            $data['productId'] = $product['id'];

            //条码判断
            if($data['code']){
                if(!preg_match($match,$data['code'])){
                    $data['error'][] = '编号含有数字英文以外的字符';
                    $data['fail'] = 1;
                    // continue;
                }else if(strlen($data['code']) < 6 || strlen($data['code']) > 30){
                    $data['fail'] = 1;
                    $data['error'][] = "条码字符长度不符合6~30";
                    // continue;
                }

                //判断自定义的条码是否重复
                $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$data['code']}' and (productId<>'{$product['id']}' or proDesc<>'{$data['proDesc']}' or type<>'{$data['type']}')";
                $tmp = $this->_subModel->findBySql($sql);
                // dump($sql);
                if($tmp[0]['cnt'] > 0){
                    $data['fail'] = 1;
                    $data['error'][] = "该条码已存在其他样品，请换一个";
                }

                //查找该条码是否相同的产品统一一个条码，不统一就清空
                $sql = "SELECT code from sample_ruku2product where productId='{$productId['id']}' and proDesc='{$data['proDesc']}' and type='{$data['type']}' limit 0,1";
                $res = $this->_subModel->findBySql($sql);
                $_code = strval($res[0]['code']);
                if($_code && $data['code']<>$_code){
                    $data['fail'] = 1;
                    $data['error'][] = "该产品之前使用的条码为{$_code}，请统一";
                }else{
                    //key
                    $_key = $data['proCode'].'-'.$data['proDesc'].'-'.$data['type'];
                    $codes[$_key][$data['code']] = $data['code'];
                    if(count($codes[$_key]) > 1){
                        $data['fail'] = 1;
                        $data['error'][] = "产品{$_key}在列表中存在多个条码，请统一或留空";
                    }
                }

            }

            //处理库位信息，如果库位信息不存在，则新增档案
            if($data['kuweiName']){
                $kuwei = $_modelKuwei->find(array('kuweiName'=>$data['kuweiName']));
                $data['kuweiId'] = $kuwei['id'] + 0;
                if(!$data['kuweiId']){
                    $_kuweiData = array(
                        'kuweiName'=>$data['kuweiName']
                    );
                    $data['kuweiId'] = $_modelKuwei->save($_kuweiData);
                }
            }

            $data['errorMsg'] = join("\n",$data['error']);
            $_data[] = $data;
        }
    }

    fclose($fh);

    return $_data;
  }

    /**
    * 按行读取文件
    * @param string $filename
    */
    function actionImportRkData($filename ,$params){
        $filename = 'upload/files/ImportData.csv';
        $fh = fopen($filename, 'r');
        $_data = array();
        $i = 0;
        $success = 0;
        $fail = 0;
        //导入的列配置
        $params['filed'] = array(
            'proCode'    => '编号',
            'proName'    => '品名',
            'chengfen'   => '成分',
            'shazhi'     => '纱支',
            'guige'      => '规格',
            'midu'       => '密度',
            'zuzhi'      => '组织',
            'menfu'      => '门幅',
            'kezhong'    => '克重',
            'gongyiName' => '后整理工艺',
            'rukuDate'   => '入库日期',
            'factoryName'=> '工厂',
            'reason'     => '来源',
            'caiyangCode'=> '采样编号',
            'price'      => '单价',
            'kuweiName'  => '库位',
            'cnt'        => '数量',
            'memoView'   => '备注',
            'code'       => '条码'
        );
        //全局做个条码，如果相同的产品条码不一致，需要提醒
        $codes = array();
        $_modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $_modelGongyi = FLEA::getSingleton('Model_Jichu_Gongyi');
        set_time_limit(0);
        while (! feof($fh)) {
            $codeNext = 0;
            $line = fgets($fh);
            if($line){
                $i++;
                if($i == 1) continue;
                $tmp = explode(',', $line);
                $data = array();
                $data['fail'] = 0;
                $index = 0;
                foreach ($params['filed'] as $key => & $v) {
                    $data[$key] = trim(iconv('GB2312', 'UTF-8', $tmp[$index])).'';
                    $index++;
                }
                // $t = array_filter($data);
                if(!$data['proCode']){
                    $data['error'][] = '无产品编号,该编号必须存在';
                    $data['fail'] = 1;
                    // continue;
                }
            //限制编号只能用数字加中英文
            // $match = "/^[a-zA-Z0-9-_\/]*$/";
            // if(!preg_match($match,$data['proCode'])){
            //     $data['error'][] = '编号含有数字英文以外的字符';
            //     $data['fail'] = 1;
            //     // continue;
            // }else
            // if(strlen($data['proCode']) < 5 || strlen($data['proCode']) > 20){
            //     $data['fail'] = 1;
            //     $data['error'][] = "产品编号字符长度不符合5~20";
            //     // continue;
            // }

            //符合条件的产品编号，需要找到是否存在于档案中，如果不存在，则需要提示错误
                $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
                $product = $modelProduct->find(array('proCode'=>$data['proCode']));
                if(!$product['id']){
                    $data['fail'] = 1;
                    $data['error'][] = "产品在基础档案中不存在，请完善";
                    // continue;
                }

                $data['productId'] = $product['id'];
                //条码判断
                if($data['code']){
                    // if(!preg_match($match,$data['code'])){
                    //     $data['error'][] = '编号含有数字英文以外的字符';
                    //     $data['fail'] = 1;
                    //     // continue;
                    // }else if(strlen($data['code']) < 6 || strlen($data['code']) > 30){
                    //     $data['fail'] = 1;
                    //     $data['error'][] = "条码字符长度不符合6~30";
                    //     // continue;
                    // }
                    //判断自定义的条码是否重复
                    $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$data['code']}' and (productId<>'{$product['id']}' or proDesc<>'{$data['proDesc']}')";
                    $tmp = $this->_subModel->findBySql($sql);
                    // dump($sql);
                    if($tmp[0]['cnt'] > 0){
                        $data['fail'] = 1;
                        $data['error'][] = "该条码已存在其他样品，请换一个";
                        // continue;
                    }

                    //查找该条码是否相同的产品统一一个条码，不统一就清空
                    $sql = "SELECT code from sample_ruku2product where productId='{$productId['id']}' and proDesc='{$data['proDesc']}' limit 0,1";
                    $res = $this->_subModel->findBySql($sql);
                    $_code = strval($res[0]['code']);
                    if($_code && $data['code']<>$_code){
                        $data['fail'] = 1;
                        $data['error'][] = "该产品之前使用的条码为{$_code}，请统一";
                        // continue;
                    }else{
                        //key
                        $_key = $data['proCode'].'-'.$data['proDesc'].'-'.$data['type'];
                        $codes[$_key][$data['code']] = $data['code'];
                        if(count($codes[$_key]) > 1){
                            $data['fail'] = 1;
                            $data['error'][] = "产品{$_key}在列表中存在多个条码，请统一或留空";
                        }
                        // continue;
                    }

                }

                // dump($data);die;
                //处理库位信息，如果库位信息不存在，则新增档案
                if($data['kuweiName']){
                    $kuwei = $_modelKuwei->find(array('kuweiName'=>$data['kuweiName']));
                    $data['kuweiId'] = $kuwei['id'] ? $kuwei['id'] : '1';
                    // if(!$data['kuweiId']){
                    //     $_kuweiData = array(
                    //         'kuweiName'=>$data['kuweiName']
                    //     );
                    //     $data['kuweiId'] = $_modelKuwei->save($_kuweiData);
                    // }
                }
                //处理库位信息，如果库位信息不存在，则新增档案
                if($data['gongyiName']){
                    $hzl = $_modelGongyi->find(array('gongyiName'=>$data['gongyiName']));
                    $data['hzlId'] = $hzl['id'] + 0;
                    if(!$data['hzlId']){
                        $_hzlData = array(
                            'gongyiName'=>$data['gongyiName']
                        );
                        $data['hzlId'] = $_modelGongyi->save($_hzlData);
                    }
                }
                if($data['code']!=''){
                    $match = "/^[a-zA-Z0-9-_\/]*$/";
                    if(!preg_match($match,$data['code'])){
                        $ret = array('msg'=>'条码含有数字英文以外的字符','success'=>false);
                        echo json_encode($ret);exit;
                    }else{
                        if(strlen($data['code']) < 6 || strlen($data['code']) > 30){
                            $ret = array('msg'=>'条码字符长度6~30','success'=>false);
                            echo json_encode($ret);exit;
                        }
                    }
                }

                //条码规则：相同productId和产品编号，类型，条码保证一致
                //先查找该样品信息是否已经存在历史条码，如果已经存在，则直接使用历史条码
                $sql = "SELECT code from sample_ruku2product where productId='{$data['productId']}' and id<>'{$data['id']}' and proDesc='{$data['proDesc']}' and type='{$data['type']}' and gexing='{$data['gexing']}' and zuzhi='{$data['zuzhi']}' and hzlId='{$data['hzlId']}' limit 0,1";
                $res = $this->_subModel->findBySql($sql);
                $_code = strval($res[0]['code']);

                //生成条码
                if($data['code'] == ''){
                    if($_code){
                        $data['code'] = $_code;
                    }else{
                        $data['code'] = $this->_modelExample->createNewCode($data,$codeNext);
                        $codeNext++;
                    }
                }else{
                    // 如果填写的条码和历史条码不一致，则需要提醒错误
                    if($_code && $data['code']<>$_code){
                        $ret = array('msg'=>'该规格类型样品有产品条码('.$_code.')，留空系统自动使用','success'=>false);
                        echo json_encode($ret);exit;
                    }
                    //查找条码是否重复:相同的产品和类型允许重复，否则不允许
                    $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$data['code']}' and (productId<>'{$data['productId']}' or proDesc<>'{$data['proDesc']}' or type<>'{$data['type']}' or gexing<>'{$data['gexing']}' or zuzhi<>'{$data['zuzhi']}' or hzlId<>'{$data['hzlId']}') and id<>'{$data['id']}'";
                    // dump($sql);exit;
                    $res = $this->_modelExample->findBySql($sql);
                    if($res[0]['cnt'] > 0){
                        $ret = array('msg'=>'条码已经被其他产品使用','success'=>false);
                        echo json_encode($ret);exit;
                    }
                }
                $data['errorMsg'] = join("\n",$data['error']);
                $data['Products'][0]['productId'] = $data['productId'] + 0;
                $data['Products'][0]['cnt'] = $data['cnt'] ? $data['cnt'] : '1';
                $data['Products'][0]['proDesc'] = $data['proDesc'].'';
                $data['Products'][0]['kuweiId'] = $kuwei['id'] ? $kuwei['id'] : '1';
                $data['Products'][0]['code'] = $data['code'].'';
                $data['Products'][0]['hzlId'] = $data['hzlId'] + 0;
                $data['Products'][0]['price'] = $data['price'];
                $data['Products'][0]['zuzhi'] = $data['zuzhi'].'';
                $last = strripos($data['code'], '-');
                $data['Products'][0]['append'] = substr($data['code'], $last+1);
                if(!$data['rukuCode']){
                    $data['rukuCode'] = $this->createNewCode();
                }
                !$data['creater'] && $data['creater'] = $_SESSION['REALNAME'];
                $data['rukuDate'] = $data['rukuDate'] ? $data['rukuDate'] :date('Y-m-d');
                $id = $this->_modelExample->save($data);
                if($id > 0){
                    $success++;
                }else{
                    $fail++;
                }
            }
        }
        fclose($fh);
        echo "导入入库记录".($i-1)."条，成功{$success}，失败{$fail}<br/>";
    }

   /**
   * 按行读取文件
   * @param string $filename
   */
  function handleData($filename ,$params){
        $fh = fopen($filename, 'r');
        $_data = array();
        $i = 0;
        //导入的列配置
        $modelPro = FLEA::getSingleton('Model_Jichu_Product');
        $params['filed'] = $modelPro->filedValue();
        //全局做个条码，如果相同的产品条码不一致，需要提醒
        $codes = array();
        $_modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');

        while (! feof($fh)) {
          $line = fgets($fh);
          if($line){
            $i++;
            if($i == 1) continue;
            $tmp = explode(',', $line);

            $data = array();
            $data['fail'] = 0;
            $index = 0;
            foreach ($params['filed'] as $key => & $v) {
                $data[$key] = trim(iconv('GB2312', 'UTF-8', $tmp[$index])).'';
                $index++;
            }

            // $t = array_filter($data);
            // dump($data);
            if(!$data['proCode']){
                $data['error'][] = '无产品编号,该编号必须存在';
                $data['fail'] = 1;
                // continue;
            }

            //限制编号只能用数字加中英文
            $match = "/^[a-zA-Z0-9-_\/]*$/";
            if(!preg_match($match,$data['proCode'])){
                $data['error'][] = '编号含有数字英文以外的字符';
                $data['fail'] = 1;
                // continue;
            }else if(strlen($data['proCode']) < 5 || strlen($data['proCode']) > 20){
                $data['fail'] = 1;
                $data['error'][] = "产品编号字符长度不符合5~20";
                // continue;
            }

            //符合条件的产品编号，需要找到是否存在于档案中，如果不存在，则需要提示错误
            $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
            $product = $modelProduct->find(array('proCode'=>$data['proCode']));
            if(!$product['id']){
                $data['fail'] = 1;
                $data['error'][] = "产品在基础档案中不存在，请完善";
                // continue;
            }

            $data['productId'] = $product['id'];

            //条码判断
            if($data['code']){
                if(!preg_match($match,$data['code'])){
                    $data['error'][] = '编号含有数字英文以外的字符';
                    $data['fail'] = 1;
                    // continue;
                }else if(strlen($data['code']) < 6 || strlen($data['code']) > 30){
                    $data['fail'] = 1;
                    $data['error'][] = "条码字符长度不符合6~30";
                    // continue;
                }

                //判断自定义的条码是否重复
                $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$data['code']}' and (productId<>'{$product['id']}' or proDesc<>'{$data['proDesc']}' or type<>'{$data['type']}')";
                $tmp = $this->_subModel->findBySql($sql);
                // dump($sql);
                if($tmp[0]['cnt'] > 0){
                    $data['fail'] = 1;
                    $data['error'][] = "该条码已存在其他样品，请换一个";
                }

                //查找该条码是否相同的产品统一一个条码，不统一就清空
                $sql = "SELECT code from sample_ruku2product where productId='{$productId['id']}' and proDesc='{$data['proDesc']}' and type='{$data['type']}' limit 0,1";
                $res = $this->_subModel->findBySql($sql);
                $_code = strval($res[0]['code']);
                if($_code && $data['code']<>$_code){
                    $data['fail'] = 1;
                    $data['error'][] = "该产品之前使用的条码为{$_code}，请统一";
                }else{
                    //key
                    $_key = $data['proCode'].'-'.$data['proDesc'].'-'.$data['type'];
                    $codes[$_key][$data['code']] = $data['code'];
                    if(count($codes[$_key]) > 1){
                        $data['fail'] = 1;
                        $data['error'][] = "产品{$_key}在列表中存在多个条码，请统一或留空";
                    }
                }

            }

            //处理库位信息，如果库位信息不存在，则新增档案
            if($data['kuweiName']){
                $kuwei = $_modelKuwei->find(array('kuweiName'=>$data['kuweiName']));
                $data['kuweiId'] = $kuwei['id'] + 0;
                if(!$data['kuweiId']){
                    $_kuweiData = array(
                        'kuweiName'=>$data['kuweiName']
                    );
                    $data['kuweiId'] = $_modelKuwei->save($_kuweiData);
                }
            }

            $data['errorMsg'] = join("\n",$data['error']);
            $_data[] = $data;
        }
    }

    fclose($fh);

    return $_data;
  }

  /**
   * 保存数据到表
   * Time：2019/12/23 09:09:37
   * @author li
   * @param 参数类型
   * @return 返回值类型
  */
  function actionSaveConfirmData(){
    $post = $this->axiosPost();
    $failData = array();
    foreach ($post['rows'] as $key => & $v) {
        //条码是否一致
        $sql = "SELECT code from sample_ruku2product where productId='{$v['productId']}' and proDesc='{$v['proDesc']}' and type='{$v['type']}' limit 0,1";
        $tmpCode = $this->_subModel->findBySql($sql);
        $_code = strval($tmpCode[0]['code']);
        if($v['code']){
            if($_code && $_code != $v['code']){
                $v['fail'] = 1;
                $v['errorMsg'] = "该产品之前使用的条码为{$_code}，请保持一致";
                $failData[] = $v;
                continue;
            }

            //条码是否重复
            $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$v['code']}' and (productId<>'{$v['productId']}' or proDesc<>'{$v['proDesc']}' or type<>'{$v['type']}')";
            $tmp = $this->_subModel->findBySql($sql);
            if($tmp[0]['cnt'] > 0){
                $v['fail'] = 1;
                $v['errorMsg'] = "该条码已存在其他样品，请换一个";
                continue;
            }
        }else{
            $v['code'] = $_code ? $_code : $this->_modelExample->createNewCode($v);
        }

        $data = array(
            'rukuCode' => $this->createNewCode(),
            'rukuDate' => date('Y-m-d'),
            'creater'  => $_SESSION['REALNAME'],
            'Products' => array()
        );

        $data['Products'][] = array(
            'productId' =>$v['productId']+0,
            'cnt'       =>$v['cnt']+0,
            'type'      =>$v['type'],
            'proDesc'   =>$v['proDesc'],
            'memoView'  =>$v['memoView'],
            'kuweiId'   =>$v['kuweiId']+0,
            'code'      =>$v['code'].'',
        );
        // dump($data);
        $id = $this->_modelExample->save($data);
        if(!$id){
            $v['fail'] = 1;
            $v['errorMsg'] = "导入出现异常";
            $failData[] = $v;
        }
    }

    // dump($failData);
    echo json_encode(array('gridData'=>$failData,'success'=>(count($failData) == 0),'msg'=>'导入数据完成'));
  }


  //获取入库中的字段，作为选择项
  function actionGetOptionsKey(){
    $params = $this->axiosPost();
    $params['key'] = strval($params['key']);
    $field = $_GET['field'];

    $sql = "SELECT distinct {$field} from sample_ruku2product where `{$field}` <> '' and `{$field}` like '%{$params['key']}%' order by `{$field}` asc ";
    $row = $this->_modelExample->findBySql($sql);

    $arr = array();
    foreach($row as & $v){
      $arr[] = array('value'=>$v[$field],'text'=>$v[$field]);
    }

    echo json_encode(array(
        'success' =>count($arr) > 0,
        'data'    =>$arr
    ));
  }

  function GetPrefix($proCode){
    dump($proCode);die;
  }


    // 动态查询条码，产品编号的信息
    function actionGetBarCodeOptions2(){
        $post = $this->axiosPost();
        // dump($post);exit;
        $sql = "SELECT x.code,x.productId,p.* from sample_ruku2product x
            left join jichu_product p on p.id=x.productId
            where 1";
        if($post['key']){
            $sql .= " and x.code like '%{$post['key']}%'";
        }
        $sql .= " group by x.code order by x.code desc limit 8";

        $list = $this->_modelExample->findBySql($sql);
        $arr = array();

        $_modelKind = FLEA::getSingleton('Model_Jichu_ProKind');
        $fileds = $_modelKind->filedsSingleGroupKind();
        // dump($fileds);exit;

        foreach($list as & $v){
            $jsonData = array(
                'productId' =>$v['productId'],
                'proName'   =>$v['proName'],
            );

            // 针对不同类型的产品，组织单列显示数据
            foreach($fileds[$v['kindId']] as & $field){
                $jsonData['proInfo'][] = array('label'=>$field['title'].':'.$v[$field['filed']]);
            }
            $arr[] = array('text'=>$v['code'] , 'value'=>$v['code'],'jsonData'=>$jsonData);
        }

        //获取条码和产品编号的信息
        echo json_encode(array(
            'success' =>count($arr) > 0,
            'data'    =>$arr
        ));
    }

    function actionCheckCode(){
        $post = $this->axiosPost();
        // dump($post);exit;
        //1.拿所有属性去查是否有条码,如果有条码,判断和当前条码是否相同,如果相同不做提醒,如果不同,则提示留空自动使用历史条码
        //2.如果没有条码,则需判断当前条码是否存在,如果存在提醒条码存在,否则直接使用
        if ($post['row']['hzlId']) {
            foreach ($post['row']['hzlId'] as $k => &$v) {
                if ($v == '') {
                    unset($post['row']['hzlId'][$k]);
                    continue;
                }
            }
            $post['row']['hzlId'] = array_values($post['row']['hzlId']);
        }
        $post['row']['hzlId'] = $post['row']['hzlId'] ? implode(',', $post['row']['hzlId']) : '';

        $rk2proIds = join(',' , array_col_values($post['row']['Products'] , 'id'));
        $where = $rk2proIds ? " and id not in({$rk2proIds})" : "";
        $sql = "SELECT code from sample_ruku2product
            where productId='{$post['row']['productId']}' and
                  proDesc='{$post['row']['proDesc']}' and
                  type='{$post['row']['type']}' and
                  gexing='{$post['row']['gexing']}' and
                  zuzhi = '{$post['row']['zuzhi']}' and
                  hzlId='{$post['row']['hzlId']}'
                  {$where}
            limit 0,1";
        // dump($sql);exit;
        $res   = $this->_subModel->findBySql($sql);
        $_code = strval($res[0]['code']);
        //生成条码
        if ($_code) {
            if ($_code == $post['row']['code']) {
                echo json_encode(array(
                    'success' => true,
                    'msg'     => '条码' . $post['row']['code'] . '可以使用',
                    'code'    => $post['row']['code'],
                ));
            } else {
                $ret = array('msg' => '该规格样品有产品条码(' . $_code . ')，留空系统自动使用', 'success' => false);
                echo json_encode($ret);exit;
            }
        } else {
            $sql = "SELECT count(*) as cnt from sample_ruku2product where code = '{$post['row']['code']}' {$where}";
            $res = $this->_modelExample->findBySql($sql);
            if ($res[0]['cnt'] > 0) {
                echo json_encode(array(
                    'success' => false,
                    'msg'     => '条码' . $post['row']['code'] . '已存在',
                ));
            } else {
                echo json_encode(array(
                    'success' => true,
                    'msg'     => '条码' . $post['row']['code'] . '可以使用',
                    'code'    => $post['row']['code'],
                ));
            }
        }
    }

    function actionGetRk2ProInfo(){
        $params = $this->axiosPost();

        $modelProduct = FLEA::getSingleton("Model_Jichu_Product");
        if($params['kind']=='ruku'){
            $ruku2pro = $this->_subModel->find(array('code'=>$params['scancode']));
            unset($ruku2pro['Rk']);
            $product = $modelProduct->find($ruku2pro['productId']);

            $pro = array_merge($product,$ruku2pro);
            $pro['proType'] = '1';
        }else{
            $pro = $modelProduct->find($params['scancode']);
        }

        if($params['kindId']){
            $row = $this->_modelKind->getFileds($params['kindId']);
        }
        $columns = array();

        if($row['single']){
            foreach ($row['single'] as $k => &$v) {
                $columns[] = $v;
            }
        }
        if($row['default']){
            foreach ($row['default'] as $k => &$v) {
                $columns[] = $v;
            }
        }
        $fileds = array();
        foreach ($columns as $key => $value) {
            $fileds[] = $value['filed'];
        }
        $pro['hzlId'] = explode(',',$pro['hzlId']);
        //返回
        echo json_encode(array(
            'success' =>$pro['id'] > 0,
            'data'    =>$pro,
            'columns' =>$fileds
        ));
    }
}

?>